package com.twu.biblioteca.book;

import com.twu.biblioteca.item.ItemDAO;
import com.twu.biblioteca.item.Items;
import com.twu.biblioteca.utils.MyFileReader;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * Created by Enrico on 10/09/2014.
 */
public class BookDAOFileImpl implements ItemDAO {

    @Override
    public Items<Book> getItems() {
        return read();
    }

    public Items<Book> read() {
        List<String> itemList = MyFileReader.read("bookList.csv");
        Iterator<String> iter = itemList.iterator();

        List<Book> bookList = new ArrayList<Book>();

        while (iter.hasNext()) {
            String[] fields = fields(iter.next());

            String title = fields[0];
            String author = fields[1];
            int year = Integer.parseInt(fields[2]);

            bookList.add(new Book(title, author, year));
        }

        return new Items<Book>(bookList);
    }

    public String[] fields(String line) {
        return line.split(",");
    }
}
